package cn.growthgate.fgo.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import cn.growthgate.fgo.common.base.BaseServiceImpl;
import cn.growthgate.fgo.entity.ServantItem;
import cn.growthgate.fgo.entity.enums.ServantItemType;
import cn.growthgate.fgo.mapper.ServantItemMapper;
import cn.growthgate.fgo.service.IServantItemService;

/**
 * <p>
 * 从者素材 服务实现类
 * </p>
 *
 * @author GrowthGate
 * @since 2019-06-19
 */
@Service
public class ServantItemServiceImpl extends BaseServiceImpl<ServantItemMapper, ServantItem>
		implements IServantItemService {

	@Override
	public boolean save(Long servantId, Long[] ids, Long[] itemIds, ServantItemType[] types, Integer[] levels,
			Integer[] numbers) {
		if (ids != null) {
			if (ids.length == 0) {
				ids = new Long[]{null};
			}
			// 旧数据id
			List<Long> oIds = selectByServantId(servantId).stream().map(ServantItem::getId)
					.collect(Collectors.toList());
			// 新数据
			List<ServantItem> nServantItems = new ArrayList<>(ids.length);
			for (int i = 0; i < ids.length; i++) {
				ServantItem servantItem = new ServantItem();
				servantItem.setId(ids[i]);
				servantItem.setServantId(servantId);
				servantItem.setItemId(itemIds[i]);
				servantItem.setType(types[i]);
				servantItem.setLevel(levels[i]);
				servantItem.setNumber(numbers[i]);
				nServantItems.add(servantItem);
				if (ids[i] != null) {
					oIds.remove(ids[i]);
				}
			}
			boolean saveSuccess = insertOrUpdateBatch(nServantItems);
			boolean deleteSuccess = deleteBatchIds(oIds);
			return saveSuccess && deleteSuccess;
		} else {
			return delete(newWrapper().eq("servantId", servantId));
		}
	}

	@Override
	public List<ServantItem> selectByServantId(Long servantId) {
		return selectList(newWrapper().eq("servantId", servantId));
	}

}
